<template>
  <el-menu
    :class="menuClass"
    :default-active="activeMenu"
    :collapse="!isCollapse"
    background-color="#304156"
    text-color="#bfcbd9"
    active-text-color="#409eff"
    @select="handleMenuSelect"
  >
    <!-- 循环渲染顶级菜单项 -->
    <template v-for="item in menuItems" :key="item.name">
      <menu-item :item="item" />
    </template>
  </el-menu>
</template>

<script setup>
import { ref, computed, onBeforeMount, watch, getCurrentInstance, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import MenuItem from '@/components/menuItem/index'
import { getMenuMap, getMenuItem } from '@/utils/index'
const { proxy } = getCurrentInstance()
const route = useRoute()

const props = defineProps({
  // 响应式侧边栏折叠状态
  isCollapse: {
    type: Boolean,
    default: false
  }
})

const menuClass = computed(() => (props.isCollapse ? 'activate__menu' : 'unactivate__menu'))

// 菜单配置数据
const menuItems = ref([])

// 当前激活菜单项
const activeMenu = ref('')

// 调用方法生成 Map
const menuMap = ref(new Map())
onBeforeMount(async () => {
  // 加载菜单数据
  const rawMenuItems = getMenuItem()

  // 解析图标组件
  menuItems.value = rawMenuItems
  // 生成菜单映射表
  menuMap.value = getMenuMap(rawMenuItems)
  // 默认选中首页
  const activedMenu = sessionStorage.getItem('activeMenu')
  if (activedMenu) {
    activeMenu.value = activedMenu
  } else {
    handleMenuSelect(0, [rawMenuItems[0].path])
  }
})

// 监听路由变化
watch(
  () => route.path,
  newPath => {
    if (menuMap.value) {
      let temp = menuMap.value.get(newPath)
      if (temp) {
        activeMenu.value = temp.path
      }
    } else {
      activeMenu.value = route.name
    }
    sessionStorage.setItem('activeMenu', activeMenu.value)
    sessionStorage.setItem('activePath', newPath)
  }
)

// 菜单选择处理
const handleMenuSelect = (index, indexPath) => {
  const menuItem = menuMap.value.get(indexPath.join(''))
  proxy.$emit('clickItem', menuItem)
  proxy.$ToPath(indexPath.join(''))
}
</script>

<style scoped>
.unactivate__menu {
  width: 56px;
}
.activate__menu {
  width: 200px;
}
.sub__menu {
  position: relative;
}
.app__menu__item .el-icon {
  left: -4px;
  margin-right: 12px;
}
</style>